package com.wephone.Student.ui;

import java.io.File;
import java.io.FileNotFoundException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.AnticipateOvershootInterpolator;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.easemob.EMCallBack;
import com.easemob.chat.EMChatManager;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.bean.SocializeEntity;
import com.umeng.socialize.bean.StatusCode;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.controller.listener.SocializeListeners.SnsPostListener;
import com.umeng.socialize.media.UMImage;
import com.wephone.Student.BaseApplication;
import com.wephone.Student.R;
import com.wephone.Student.bean.GroupDetailsResponse;
import com.wephone.Student.bean.GroupInfoDetailResponse;
import com.wephone.Student.bean.GroupResponse;
import com.wephone.Student.bean.RegisterResponse;
import com.wephone.Student.bean.data.CountryData;
import com.wephone.Student.bean.data.GroupInfo;
import com.wephone.Student.bean.data.UserInfoData;
import com.wephone.Student.network.HttpClient;
import com.wephone.Student.network.MyResponseHandler;
import com.wephone.Student.util.Constants;
import com.wephone.Student.util.MD5;
import com.wephone.Student.util.RoundImageView;
import com.wephone.Student.util.ShareReferenceUtil;
import com.wephone.Student.util.Util;
import com.wephone.Student.wheel.widget.StringWheelAdapter;
import com.wephone.Student.wheel.widget.WheelView;

public class NewGroupActivity2 extends BaseActivity{
	private String groupName;
	private String groupDesc;
	private int groupType;
	private String type;
	private String groupLoc;
	private TextView groupLocTxt;
	private File photoSavedFile = null;
	private String photoSavedName = null;
	private RoundImageView groupPhoto;
	private ProgressDialog progressDialog;
	private LinearLayout reg_layout_1;

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(requestCode==1){
			if(photoSavedFile!=null && photoSavedFile.exists()){
				Bitmap bitmap = Util.getBitmap(getApplicationContext(),photoSavedFile.getPath(),300);
				
				Bitmap newBitmap = Util.compressImage(bitmap);
       		 	groupPhoto.setImageBitmap(newBitmap);
       		 	Util.saveMyBitmap(newBitmap,photoSavedName,getApplicationContext());
			}else if(data!=null){
				Bundle bundle = data.getExtras();
				if(bundle!=null){
					Bitmap tmpbitmap = (Bitmap)bundle.get("data");
					Bitmap newBitmap = Util.comp(tmpbitmap);
					if(tmpbitmap!=null){
						groupPhoto.setImageBitmap(newBitmap);
		       		 	Util.saveMyBitmap(newBitmap,photoSavedName,getApplicationContext());
					}
				}
			}
   	 	}else if(requestCode==2){
	   	 	if(data!=null){
	   		 	Uri selectedImage = data.getData();
		        String[] filePathColumn = {MediaStore.Images.Media.DATA};
		        Cursor cursor = getContentResolver().query(selectedImage,filePathColumn, null, null, null);
		        cursor.moveToFirst();
		        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
		        String picturePath = cursor.getString(columnIndex);
		        cursor.close();
		        if(!TextUtils.isEmpty(picturePath)){
		        	 File userLogoFile = new File(picturePath);  
		        	 if(userLogoFile.exists()){
		        		 Bitmap bitmap = Util.getBitmap(getApplicationContext(),picturePath,300);
		        		 Bitmap newBitmap = Util.compressImage(bitmap);
		        		 groupPhoto.setImageBitmap(newBitmap);
		        		 Util.saveMyBitmap(bitmap,photoSavedName,getApplicationContext());
		        	 }
		         }
	   	 	}
   	 	}
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_new_group_2);
		
		Bundle bundle = getIntent().getExtras();
		if(bundle!=null){
			
			groupName = bundle.getString("groupName");
			groupDesc = bundle.getString("groupDesc");
			groupType = bundle.getInt("groupType");
			if(groupType==1){
				type="出国交流";
			}else if(groupType ==2){
				type="海龟交流";
			}else{
				type="国外交流";
			}
		}
		init();
		
	}
	
	private void init(){
		String pathString;
		if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
        {
			
			pathString = Constants.IMAGE_PHOTO_TMP_PATH;
        }else{
        	
        	pathString = getApplicationContext().getCacheDir().getAbsolutePath()+"/";
        }
		photoSavedName = "grouplogo_"+System.currentTimeMillis()+".jpg";
		photoSavedFile = new File(pathString+photoSavedName);
		groupPhoto = (RoundImageView)findViewById(R.id.user_logo_image);
		groupLocTxt = (TextView)findViewById(R.id.groupLoc);
		
		TextView  user_name_text = (TextView)findViewById(R.id.user_name_text);
		user_name_text.setText(groupName);
		findViewById(R.id.btn_back).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				setResult(-1);
				finish();
			}
		});
		DisplayImageOptions options = new DisplayImageOptions.Builder()
	    .showStubImage(R.drawable.default_user_logo)
	    .showImageOnFail(R.drawable.default_user_logo)
	    .bitmapConfig(Bitmap.Config.ARGB_8888)
	    .cacheInMemory()
	    .cacheOnDisc()
//	    .displayer(new RoundedBitmapDisplayer(1000))
	    .build();
		UserInfoData myInfo = BaseActivity.getMyInfo(getApplicationContext());
		imageLoader.displayImage(Constants.IMAGE_PHOTO_SERVER_PATH+myInfo.getuIcon(), groupPhoto, options);
		
		findViewById(R.id.reg_layout_1).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				new AlertDialog.Builder(NewGroupActivity2.this).setTitle("选择群头像")
				.setItems(new String[]{"拍照","相册"}, new DialogInterface.OnClickListener(){
					@Override
					public void onClick(DialogInterface arg0, int arg1) {
				
						if(arg1==0){
					
							Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
							intent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(photoSavedFile));
							//intent.putExtra(MediaStore.EXTRA_OUTPUT,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
		                    intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
		                    startActivityForResult(intent, 1);
						}else{
							
							Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
							startActivityForResult(i, 2);
						}
					}})
				.setNegativeButton("取消", null).show();
			}
		});
		
		findViewById(R.id.btn_next_step).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				
				if(photoSavedFile==null || !photoSavedFile.exists()){
					Util.saveMyBitmap(((BitmapDrawable)groupPhoto.getDrawable()).getBitmap(),photoSavedName,getApplicationContext());
				}
				if(TextUtils.isEmpty(groupLoc)){
					Toast.makeText(getApplicationContext(), "请选择群组所在地", Toast.LENGTH_SHORT).show();
					return;
				}
				
				RequestParams params = new RequestParams();
				params.put("uId", BaseActivity.getMyInfo(getApplicationContext()).getuId());
				params.put("name", groupName);
				params.put("content", groupDesc);
				params.put("statu", "1");
				params.put("type", type);
				params.put("clog", groupLoc);
				if( photoSavedFile!=null && photoSavedFile.exists()){
					try {
						params.put("pic", photoSavedFile);
					} catch (FileNotFoundException e) {
						e.printStackTrace();
					}
				}else{
					try {
						params.put("pic", photoSavedFile);
					} catch (FileNotFoundException e) {
						e.printStackTrace();
					}
				}
				progressDialog = ProgressDialog.show(NewGroupActivity2.this, "提示", "正在提交数据...", true, false);
				HttpClient.getInstance().post(Constants.API_ADD_CHART_URL, params, getHandler());
//				bundle.putString("photoSavedPath", photoSavedFile.getPath());
//				startActivity(new Intent(getApplicationContext(),NewRegisterActivity3.class));
			}
		});
		
		findViewById(R.id.reg_layout_2).setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				showChooseCountryDialog("群所在地");
			}
			
		});
	}
	
	private void showChooseCountryDialog(String title){
		View inputView = getLayoutInflater().inflate(R.layout.dialog_wheel_1_view, null);
		final WheelView wheel = (WheelView)inputView.findViewById(R.id.wheel_1);
		List<String> countryList = new ArrayList<String>();
		for(CountryData cd:BaseActivity.getCountryList(getApplicationContext())){
			countryList.add(cd.getN());
		}
        wheel.setAdapter(new StringWheelAdapter(countryList));
        wheel.setCurrentItem(1);
        wheel.setCyclic(true);
        wheel.setInterpolator(new AnticipateOvershootInterpolator());
		AlertDialog.Builder builder = new AlertDialog.Builder(NewGroupActivity2.this);
		builder.setTitle(title);
		builder.setView(inputView);  
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener(){  
			public void onClick(DialogInterface dialog, int whichButton){
				int countryIdx = wheel.getCurrentItem();
				groupLoc = BaseActivity.getCountryList(getApplicationContext()).get(countryIdx).getN();
				groupLocTxt.setText(groupLoc);
			}
		});  
		builder.setNegativeButton("取消", new DialogInterface.OnClickListener(){  
			public void onClick(DialogInterface dialog, int whichButton){}
		}); 
		builder.show();  
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			setResult(-1);
			finish();
			return true; 
       }
       return super.onKeyDown(keyCode, event);
	}
	
	private MyResponseHandler getHandler(){
		MyResponseHandler handler = new MyResponseHandler(NewGroupActivity2.this,GroupResponse.class){
			@Override
			public void onSuccess(String result) {
				super.onSuccess(result);
				
				if(progressDialog!=null){
					progressDialog.dismiss();
				}
				if(getDataSuccess){
					GroupResponse res = (GroupResponse)response;
					if(res.getData().length()>0){
							//login huanxin account
							Toast.makeText(getApplicationContext(), "创建成功", Toast.LENGTH_SHORT).show();
							RequestParams params2 = new RequestParams();
							params2.put("groupid", res.getData());
							params2.put("uId",BaseActivity.getMyInfo(NewGroupActivity2.this).getuId());
							HttpClient.getInstance().get(Constants.API_GET_CHART_DETAIL, params2, new MyResponseHandler(NewGroupActivity2.this, GroupDetailsResponse.class){
								@Override
								public void onSuccess(String result) {
									super.onSuccess(result);
									GroupInfo groupDataGroupInfo = ((GroupDetailsResponse)response).getData();
									Intent intent = new Intent(getApplicationContext(),GroupInviteActivity.class);
									//intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
									Bundle bundle = new Bundle();
									bundle.putSerializable("groupData", groupDataGroupInfo);
									intent.putExtras(bundle);
									OnlineActivity.needRefresh = true;
									startActivity(intent);
									setResult(3);
									finish();
								}
							});
							
					}else{
						 Toast.makeText(getApplicationContext(), "创建失败", Toast.LENGTH_SHORT).show();
					}
					
					if(photoSavedFile!=null && photoSavedFile.exists()){
						photoSavedFile.delete();
					}
				}
			}

			@Override
			public void onFailure(Throwable arg0, String result) {
				super.onFailure(arg0, result);
				
				if(progressDialog!=null){
					progressDialog.dismiss();
				}
				Toast.makeText(getApplicationContext(), getString(R.string.network_error_txt), Toast.LENGTH_SHORT).show();
			}
			
			
		};
		return handler;
	}
	
}
